package hsrt.com.dynamiccomponent_android.dynamic_component;

import android.util.Pair;

import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chad.library.adapter.base.entity.MultiItemEntity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 1 添加验证的功能  √
 * 2 批量添加和删除
 * 3 合并component和holder,以便于验证, √
 * 4 解析的部分需要进行处理
 */

public class DynamicDisplayManager {


    public interface DynamicDisplayManagerListener {

        /**
         * 返回当前的adapter
         *
         * @return .
         */
        BaseMultiItemQuickAdapter<MultiItemEntity, BaseViewHolder> getAdapter();


        /**
         * 上传的时候验证失败,会调用当前方法.
         *
         * @param preUploadData 将要上传的数据
         * @param failMsg       失败的时候错误信息
         */
        void validationFail(Map<String, Object> preUploadData, String failMsg);

    }

    private DynamicDisplayManagerListener listener;
    private DynamicParserInterface parser;
    private DataElementInterface dataElementLinkList;
    private DataToItemMapper itemMapper;
    private boolean flagModify;//列表是否可编辑
    public EventManager eventManager = new EventManager();

    public DynamicDisplayManager(DynamicDisplayManagerListener listener, DynamicParserInterface parser, boolean flagModify) {
        this.listener = listener;
        this.parser = parser;
        this.itemMapper = new DataToItemMapper();
        this.flagModify = flagModify;
    }

    public void registerItem(ArrayList<DynamicComponentInterface> dynamicComponentInterfaces) {
        itemMapper.registerItem(dynamicComponentInterfaces, this);
    }

    /**
     * 输入数据
     *
     * @param data .
     */
    public void putData(List data, Map<String, Object> recordViewValueMap) {
        if (listener != null && parser != null) {
            parser.getDataElementLinkListWithData(flagModify, data, recordViewValueMap, new DynamicParserInterface.DynamicParserSuccessInterface() {
                @Override
                public void getSuccess(DataElementInterface dataElement) {
                    dataElementLinkList = dataElement;
                    //由双链表转化成数组
                    BaseMultiItemQuickAdapter<MultiItemEntity, BaseViewHolder> adapter = listener.getAdapter();

                    List<? extends MultiItemEntity> multiItemEntityArrayList = LinkListHelper.getListWithLinkList((DataElement) dataElementLinkList);

                    if (multiItemEntityArrayList != null && !multiItemEntityArrayList.isEmpty() && adapter != null) {
                        adapter.setNewData((ArrayList<MultiItemEntity>) multiItemEntityArrayList);
                        adapter.expandAll();
                    }
                }
            });
        }
    }


    /**
     * 批量增加
     *
     * @param dataElement .
     * @param position    .
     */
    public void batchC(DataElementInterface dataElement, int position) {
        //todo 1 向链表插入数据 2 生成新的数组然后刷新  3 更新ui
        if (dataElementLinkList == null) {
            return;
        }
        //务必先在插入链表前得到数据,否则插入链表的时候会得到链表的内容.
        List<? extends MultiItemEntity> newData = LinkListHelper.getSimpleListWithLinkList((DataElement) dataElement);
        //同步数据到链表
        dataElementLinkList = LinkListHelper.insertDataElement(dataElement, position, dataElementLinkList);


        if (listener != null) {
            BaseMultiItemQuickAdapter<MultiItemEntity, BaseViewHolder> adapter = listener.getAdapter();
            adapter.addData(position, newData);
        }
    }

    /**
     * 批量删除 (不能删除root元素,否则会出现问题)
     *
     * @param childRootDataElement .
     * @param position             .
     */
    //删除有问题,删除应该是同样批次的cell呗删除,而现在是删除了所有 ,所以不对.
    public void batchD(DataElementInterface childRootDataElement, int position) {

        if (dataElementLinkList == null) {
            return;
        }
        Pair<DataElementInterface, Integer> dataElementPair = LinkListHelper.deleteChildObjectDataElement(childRootDataElement, dataElementLinkList);
        if (dataElementPair == null) {
            return;
        }
//        dataElementLinkList = dataElementPair.first;
        int count = dataElementPair.second;

        if (listener != null) {
            BaseMultiItemQuickAdapter<MultiItemEntity, BaseViewHolder> adapter = listener.getAdapter();
            List<MultiItemEntity> datas = adapter.getData();
            for (int i = 0; i <= count; i++) {
                datas.remove(position + i);
            }
            adapter.notifyItemRangeRemoved(position, count + 1);
        }
    }


    /**
     * 获取类型和id的字典
     *
     * @return .
     */
    public Map<Integer, Integer> getTypeAndId() {
        return itemMapper == null ? null : itemMapper.getTypeAndId();
    }


    /**
     * 处理每个item的配置工作
     *
     * @param holder .
     * @param item   .
     */
    public void process(BaseViewHolder holder, MultiItemEntity item, BaseQuickAdapter adapter) {
        DynamicComponentInterface dynamicComponentInterface = itemMapper.getDynamicComponent(holder.getItemViewType());
        //在这里注册component和dataelement的关系,但是需要注意的是component只是一个处理单元,所以具体接收的时候还要根据dataelement进行过滤.
        if (eventManager != null && dynamicComponentInterface instanceof EventManager.Subscriber) {
            eventManager.registerSubscriber((DataElementInterface) item, (EventManager.Subscriber) dynamicComponentInterface);
        }
        dynamicComponentInterface.process(holder, item, adapter, flagModify);
    }


    /**
     * 获取上传的信息,如果某item的信息出现错误,就返回null.
     *
     * @return .
     */
    public Map<String, Object> getSubmitForm() {
        if (dataElementLinkList == null) {
            return null;
        }
        HashMap<String, Object> result = new HashMap<>();
        DataElementInterface temp = this.dataElementLinkList;
        while (temp != null) {
            Map<String, Object> submitData = temp.getSubmitData();
            if (submitData == null) {
                temp = temp.getNext();
                continue;
            }
            String msg = temp.validationWithData(submitData);
            if (msg != null && !msg.isEmpty()) {
                if (listener != null) {
                    listener.validationFail(submitData, msg);
                    return null;
                }
            } else {
                result.putAll(submitData);
            }
            temp = temp.getNext();
        }

        return result;
    }

    /**
     * 给订阅者们发送消息
     *
     * @param dataElements 订阅者们
     * @param sender       发送者
     * @param data         数据内容
     */
    public void sendNext(List<DataElementInterface> dataElements, DataElementInterface sender, String data) {
        for (DataElementInterface dataElement : dataElements) {
            eventManager.sendNext(dataElement, sender, data);
        }
    }
}
